/**
 * Project oo_thread
 */


#include "Thread.h"
#include <string.h>
#include <unistd.h>
#include <stdio.h>
/**
 * Thread implementation
 */


Thread::Thread(Task * task)
:_isRunning(false)
,_task(task)
{

}
Thread::~Thread()
{

}

/**
 * @return void
 */
void Thread::start() {
    //创建线程
    int ret = pthread_create(&_pthid, NULL, start_routine, this);
    if(0 != ret)
    {
        fprintf(stderr, "pthread_create: %s\n", strerror(ret));
        return;
    }
    _isRunning = true;
}

/**
 * @return void
 */
void Thread::join() {
    if(_isRunning)
    {
        pthread_join(_pthid,NULL);
    }
}

//在start直接执行入口函数
void * Thread::start_routine(void * arg)
{
    Thread *th = static_cast<Thread *> (arg);
    if(th)
        th->run();

    return nullptr;
}

void Thread::run()
{
    if(_task)
    {
        _task->process();
    }

}
